import numpy as np


def practice_1():
  a = np.array([1, 2, 3])
  b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  b[1, 1] = 10
  print(a.shape)
  print(b.shape)
  print(a.dtype)
  print(b)


def practice_2():
  persontype = np.dtype({
    'names': ['name', 'age', 'chinese', 'math', 'english'],
    'formats': ['S32', 'i', 'i', 'i', 'f']})
  peoples = np.array(
      [("ZhangFei", 32, 75, 100, 90), ("GuanYu", 24, 85, 96, 88.5),
       ("ZhaoYun", 28, 85, 92, 96.5), ("HuangZhong", 29, 65, 85, 100)],
      dtype=persontype)
  ages = peoples[:]['age']
  chineses = peoples[:]['chinese']
  maths = peoples[:]['math']
  englishs = peoples[:]['english']
  print(np.mean(ages))
  print(np.mean(chineses))
  print(np.mean(maths))
  print(np.mean(englishs))


def practice_3():
  x1 = np.arange(1, 11, 2)
  x2 = np.linspace(1, 9, 5)
  print(x1)
  print(x2)


def practice_4():
  x1 = np.arange(1, 11, 2)
  x2 = np.linspace(1, 9, 5)
  print(np.add(x1, x2))
  print(np.subtract(x1, x2))
  print(np.divide(x1, x2))
  print(np.power(x1, x2))
  print(np.remainder(x1, x2))


def practice_5():
  a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  # amin的作用是返回数组中的最小值
  print(np.amin(a))
  # axis=0 表示沿着第0轴（即按列）计算最小值
  print(np.amin(a, 0))
  print(np.amin(a, 1))
  # 注释掉这行，因为对于二维数组来说，axis=2 超出了维度范围（只有 axis=0 和 axis=1 有效）
  #print(np.amin(a, 2))

  # peak to peak: 最大值与最小值之差
  a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  print(np.ptp(a))
  print(np.ptp(a, 0))
  print(np.ptp(a, 1))

  # 分位数:
  a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  print(np.percentile(a, 50))
  print(np.percentile(a, 50, axis=0))
  print(np.percentile(a, 50, axis=1))

  # 加权平均
  a = np.array([1, 2, 3, 4])
  wts = np.array([1, 2, 3, 4])
  print(np.average(a))
  print(np.average(a, weights=wts))

  # 标准差方差
  a = np.array([1, 2, 3, 4])
  print(np.std(a))
  print(np.var(a))


def practice_6():
  a = np.array([[4, 3, 2], [2, 4, 1]])
  # 对数组a进行排序，不指定轴时默认按最后一轴（axis=-1）排序
  print(np.sort(a))
  # 将数组展平为一维后进行排序
  print(np.sort(a, axis=None))
  # 沿着第0轴（跨行）进行排序，即对每一列进行排序
  print(np.sort(a, axis=0))
  # 沿着第1轴（跨列）进行排序，即对每一行进行排序
  print(np.sort(a, axis=1))

def practice_ext():
  arr_3d = np.arange(24).reshape(2, 3, 4)
  print("三维数组形状:", arr_3d.shape)
  print("三维数组内容:")
  print(arr_3d)

  # 沿各轴求和
  print("axis=0 (跨页求和):", arr_3d.sum(axis=0).shape)
  print("axis=1 (跨行求和):", arr_3d.sum(axis=1).shape)
  print("axis=2 (跨列求和):", arr_3d.sum(axis=2).shape)
  print("axis=-1 (最后一轴求和):", arr_3d.sum(axis=-1).shape)


if __name__ == '__main__':
  practice_ext()
